package com.paradoxie.autoscrolltextview;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import java.util.ArrayList;

public class VerticalTextView extends TextSwitcher implements ViewSwitcher.ViewFactory {

    private static final int FLAG_START_AUTO_SCROLL = 0;
    private static final int FLAG_STOP_AUTO_SCROLL = 1;
    private PointF mDownPoint = new PointF();
    private float mTextSize = 16 ;
    private int mPadding = 5;
    private int mTextColor = Color.BLACK;
    private int mLines = 1;
    private float mTextHeight = 0;
    private OnItemClickListener itemClickListener;
    private Context mContext;
    private int groupIndex = -1;
    private ArrayList<String> textList = new ArrayList<String>();;
    private Handler handler;

    public VerticalTextView(Context context) {
        this(context, null);
        mContext = context;
    }

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public void setProperty(float textSize, int padding, int textColor, long animDuration, int lines) {
        mTextSize = textSize;
        mPadding = padding;
        mTextColor = textColor;
        mLines = lines;

        // 计算字体高度
        Paint p = new Paint();
        p.setColor(textColor);
        p.setTextSize(dip2px(mContext, textSize));
        p.setTextAlign(Paint.Align.CENTER);
        Paint.FontMetrics fm = p.getFontMetrics();
        mTextHeight = (Math.abs(fm.top) + Math.abs(fm.descent)) * mLines;

        // 设置出入动画
        setFactory(this);
        Animation in = new TranslateAnimation(0, 0, mTextHeight, 0);
        in.setDuration(animDuration);
        in.setInterpolator(new AccelerateInterpolator());
        Animation out = new TranslateAnimation(0, 0, 0, -mTextHeight);
        out.setDuration(animDuration);
        out.setInterpolator(new AccelerateInterpolator());
        setInAnimation(in);
        setOutAnimation(out);
    }

    /**
     * 间隔时间
     */
    public void initAutoScroll(final long stickTime){
       handler =new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case FLAG_START_AUTO_SCROLL:
                        int size = textList.size();
                        if (size > 0) {
                            if (groupIndex + 1 < Math.ceil((double)size / (double)mLines)) {
                                groupIndex++;
                            } else {
                                groupIndex = 0;
                            }

                            String showText = "";
                            int count = (groupIndex + 1) * mLines;
                            for (int i = groupIndex * mLines; i < count && i < size; i++) {
                                showText += (textList.get(i) + "\n");
                            }
                            if (!TextUtils.isEmpty(showText)) {
                                showText = showText.substring(0, showText.length() - 1);
                            }

                            setText(showText);
                        }
                        handler.sendEmptyMessageDelayed(FLAG_START_AUTO_SCROLL, stickTime);
                        break;
                    case FLAG_STOP_AUTO_SCROLL:
                        handler.removeMessages(FLAG_START_AUTO_SCROLL);
                        break;
                }
            }
        };
    }
    /**
     * 设置数据源
     */
    public void setTextList(ArrayList<String> titles) {
        textList.clear();
        textList.addAll(titles);
        groupIndex = -1;
    }

    /**
     * 开始滚动
     */
    public void startAutoScroll() {
        if (handler != null) {
            handler.sendEmptyMessage(FLAG_START_AUTO_SCROLL);
        }
    }

    /**
     * 停止滚动
     */
    public void stopAutoScroll() {
        if (handler != null) {
            handler.sendEmptyMessage(FLAG_STOP_AUTO_SCROLL);
        }
    }

    @Override
    public View makeView() {
        TextView t = new TextView(mContext);
        t.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
        t.setMaxLines(mLines);
        t.setPadding(mPadding, mPadding, mPadding, mPadding);
        t.setTextColor(mTextColor);
        t.setTextSize(mTextSize);

        // 如果可以单击某条目
        t.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent evt) {

                switch (evt.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 记录按下时候的坐标
                        mDownPoint.x = evt.getX();
                        mDownPoint.y = evt.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        // 在up时判断是否按下和松手的坐标为一个点
                        if (PointF.length(evt.getX() - mDownPoint.x, evt.getY()
                                - mDownPoint.y) < (float) 5.0) {
                            float unitHeight = mTextHeight / mLines;
                            for (int i = 0; i < mLines; i++) {
                                if (evt.getY() > 0 && evt.getY() < unitHeight * (i + 1)) {
                                    if (itemClickListener != null && textList.size() > 0) {
                                        itemClickListener.onItemClick(groupIndex * mLines + i);
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                }

                return true;
            }
        });

        return t;
    }

    /**
     * 设置点击事件监听
     */
    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    /**
     * 轮播文本点击监听器
     */
    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public float dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return dpValue * scale + 0.5f;
    }
}
